import { useLocation, useNavigate } from 'react-router-dom';
import { menuApi } from '@/services/menuApi';
import CloudIcon from './CloudIcon';
import { Palette, User, UserCheck, Shield, RefreshCw, ChevronDown, Upload, GitBranch, Users, FolderOpen, Clock, Folder, Eye, HardDrive, Star, Globe, X, Database, Share2, Menu, Home, Download, Settings, MenuSquare, HelpCircle, FileText, Code, ChevronRight, LogOut } from 'lucide-react';
import { userApi } from '@/services/api';
import React, { useCallback, useEffect, useRef, useMemo, useState } from 'react';
import { DropdownMenuItem, DropdownMenuTrigger, DropdownMenuContent, DropdownMenu, DropdownMenuSeparator } from '@/components/ui/dropdown-menu';
import RoleSwitchDialog from './RoleSwitchDialog';
import { Button } from '@/components/ui/button';

const Sidebar = ({ isOpen, onToggle }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [expandedItems, setExpandedItems] = useState([]);
  const [activeItem, setActiveItem] = useState('');
  const [activeParentItem, setActiveParentItem] = useState(null);
  const [userInfo, setUserInfo] = useState(null);
  const [isLoadingUserInfo, setIsLoadingUserInfo] = useState(false);
  const [showRoleSwitchDialog, setShowRoleSwitchDialog] = useState(false);
  const [menuItems, setMenuItems] = useState([]);
  const [isLoadingMenu, setIsLoadingMenu] = useState(true);
  
  const isInitialRender = useRef(true);
  const previousLocation = useRef(location.pathname);

  const iconMap = {
    'FolderOpen': FolderOpen,
    'Home': Home,
    'Share2': Share2,
    'Star': Star,
    'Eye': Eye,
    'HardDrive': HardDrive,
    'Clock': Clock,
    'FileText': FileText,
    'Globe': Globe,
    'Code': Code,
    'Database': Database,
    'GitBranch': GitBranch,
    'Palette': Palette,
    'Settings': Settings,
    'Download': Download,
    'MenuSquare': MenuSquare,
    'Shield': Shield,
    'Users': Users,
    'UserCheck': UserCheck,
    'User': User,
    'HelpCircle': HelpCircle,
    'Upload': Upload,
    'Folder': Folder
  };

  const getIconComponent = (iconName) => {
    return iconMap[iconName] || FileText;
  };

  const transformMenuData = (menuData) => {
    if (!menuData || !Array.isArray(menuData)) {
      return [];
    }

    return menuData
      .filter(item => item.isEnabled === 1)
      .map(item => {
        const IconComponent = getIconComponent(item.icon);
        
        const transformedItem = {
          id: item.menuCode,
          title: item.menuName,
          icon: IconComponent,
          path: item.webPath || null
        };

        if (item.child && Array.isArray(item.child) && item.child.length > 0) {
          transformedItem.children = item.child
            .filter(child => child.isEnabled === 1)
            .map(child => {
              const ChildIconComponent = getIconComponent(child.icon);
              return {
                id: child.menuCode,
                title: child.menuName,
                path: child.webPath,
                icon: ChildIconComponent
              };
            });
        }

        return transformedItem;
      });
  };

  const fetchMenuData = useCallback(async () => {
    setIsLoadingMenu(true);
    try {
      const response = await menuApi.getSelfMenu();
      if (response.code === "200" && response.msg === "success" && response.data) {
        const transformedMenu = transformMenuData(response.data);
        setMenuItems(transformedMenu);
      }
    } catch (error) {
      console.error('获取菜单数据失败:', error);
      setMenuItems([]);
    } finally {
      setIsLoadingMenu(false);
    }
  }, []);

  const fetchUserInfo = useCallback(async () => {
    setIsLoadingUserInfo(true);
    try {
      const response = await userApi.getSelfInfo();
      if (response.code === "200" && response.msg === "success" && response.data) {
        setUserInfo(response.data);
        
        const storage = localStorage.getItem('authToken') ? localStorage : sessionStorage;
        storage.setItem('userInfo', JSON.stringify(response.data));
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      setUserInfo({
        nickName: '用户',
        currentRoleName: '普通用户',
        email: '',
        enabled: true
      });
    } finally {
      setIsLoadingUserInfo(false);
    }
  }, []);

  useEffect(() => {
    const storage = localStorage.getItem('authToken') ? localStorage : sessionStorage;
    const cachedUserInfo = storage.getItem('userInfo');
    
    if (cachedUserInfo) {
      try {
        setUserInfo(JSON.parse(cachedUserInfo));
      } catch (error) {
        console.error('解析缓存的用户信息失败:', error);
      }
    }
    
    fetchUserInfo();
    fetchMenuData();
  }, [fetchUserInfo, fetchMenuData]);

  useEffect(() => {
    const currentPath = location.pathname;
    
    if (previousLocation.current === currentPath && !isInitialRender.current) {
      return;
    }
    
    for (const item of menuItems) {
      if (item.children) {
        for (const child of item.children) {
          if (child.path === currentPath) {
            setActiveItem(prevActive => {
              if (prevActive === child.id) return prevActive;
              return child.id;
            });
            
            setActiveParentItem(prevParent => {
              if (prevParent === item.id) return prevParent;
              return item.id;
            });
            
            setExpandedItems(prevExpanded => {
              const newExpanded = [item.id];
              if (prevExpanded.length === 1 && prevExpanded[0] === item.id) {
                return prevExpanded;
              }
              return newExpanded;
            });
            
            previousLocation.current = currentPath;
            isInitialRender.current = false;
            return;
          }
        }
      }
    }
    
    previousLocation.current = currentPath;
    isInitialRender.current = false;
  }, [location.pathname, menuItems]);

  const toggleExpanded = useCallback((itemId) => {
    setExpandedItems(prev => {
      const isCurrentlyExpanded = prev.includes(itemId);
      
      if (isCurrentlyExpanded) {
        const newExpanded = prev.filter(id => id !== itemId);
        return newExpanded.length === prev.length ? prev : newExpanded;
      } else {
        const newExpanded = [itemId];
        return prev.length === 1 && prev[0] === itemId ? prev : newExpanded;
      }
    });
  }, []);

  const handleChildClick = useCallback((child) => {
    requestAnimationFrame(() => {
      setActiveItem(child.id);
      
      setTimeout(() => {
        navigate(child.path);
        if (window.innerWidth < 1024) {
          onToggle();
        }
      }, 0);
    });
  }, [navigate, onToggle]);

  const handleClose = useCallback(() => {
    onToggle();
  }, [onToggle]);

  const handleSwitchRole = useCallback((e) => {
    if (e) {
      e.preventDefault();
      e.stopPropagation();
    }
    
    if (!showRoleSwitchDialog) {
      setShowRoleSwitchDialog(true);
    }
  }, [showRoleSwitchDialog]);

  const handleRoleSwitch = useCallback((roleId, roleName) => {
    setUserInfo(prev => prev ? {
      ...prev,
      currentRoleId: roleId,
      currentRoleName: roleName
    } : null);
    
    console.log(`角色已切换到：${roleName}`);
    
    fetchMenuData();
  }, [fetchMenuData]);

  const handleLogout = useCallback((e) => {
    if (e) {
      e.preventDefault();
      e.stopPropagation();
    }
    
    console.log('用户注销登录');
    localStorage.removeItem('authToken');
    localStorage.removeItem('refreshToken');
    localStorage.removeItem('tokenExpires');
    localStorage.removeItem('userInfo');
    sessionStorage.removeItem('authToken');
    sessionStorage.removeItem('refreshToken');
    sessionStorage.removeItem('tokenExpires');
    sessionStorage.removeItem('userInfo');
    navigate('/authority/login');
    if (window.innerWidth < 1024) {
      onToggle();
    }
  }, [navigate, onToggle]);

  const handleProfileClick = useCallback((e) => {
    if (e) {
      e.preventDefault();
      e.stopPropagation();
    }
    
    navigate('/setting/profile');
    if (window.innerWidth < 1024) {
      onToggle();
    }
  }, [navigate, onToggle]);

  const handleRoleSwitchDialogChange = useCallback((open) => {
    setShowRoleSwitchDialog(open);
    
    if (!open) {
      setTimeout(() => {
        document.body.style.pointerEvents = '';
      }, 300);
    }
  }, []);

  const MenuItemComponent = useCallback(({ item }) => {
    const isExpanded = expandedItems.includes(item.id);
    const isActiveParent = activeParentItem === item.id;
    
    return (
      <div className="space-y-2">
        <button
          onClick={() => toggleExpanded(item.id)}
          className={`w-full flex items-center justify-between p-4 rounded-xl group border border-transparent ${
            isActiveParent 
              ? '' 
              : 'hover:bg-gradient-to-r hover:from-material-grey-50 hover:to-material-grey-100 hover:border-material-grey-200'
          }`}
          style={{
            transition: 'none'
          }}
        >
          <div className="flex items-center space-x-4">
            <div className={`w-10 h-10 bg-gradient-to-br from-material-grey-100 to-material-grey-200 rounded-xl flex items-center justify-center ${
              isActiveParent 
                ? 'from-primary/10 to-primary/20' 
                : 'group-hover:from-primary/10 group-hover:to-primary/20'
            }`}
            style={{ transition: 'none' }}
            >
              <item.icon className={`w-5 h-5 ${
                isActiveParent 
                  ? 'text-primary' 
                  : 'text-material-grey-600 group-hover:text-primary'
              }`} 
              style={{ transition: 'none' }}
              />
            </div>
            <div className="text-left">
              <span className={`text-sm font-semibold block ${
                isActiveParent 
                  ? 'text-material-grey-900' 
                  : 'text-material-grey-700 group-hover:text-material-grey-900'
              }`}
              style={{ transition: 'none' }}
              >
                {item.title}
              </span>
              <span className={`text-xs ${
                isActiveParent 
                  ? 'text-material-grey-600' 
                  : 'text-material-grey-500 group-hover:text-material-grey-600'
              }`}
              style={{ transition: 'none' }}
              >
                {item.children?.length || 0} 个选项
              </span>
            </div>
          </div>
          {item.children && (
            <div className={`p-1 rounded-lg ${
              isActiveParent 
                ? 'bg-white/50' 
                : 'group-hover:bg-white/50'
            }`}
            style={{ transition: 'none' }}
            >
              {isExpanded ? (
                <ChevronDown className={`w-4 h-4 ${
                  isActiveParent 
                    ? 'text-primary' 
                    : 'text-material-grey-500 group-hover:text-primary'
                }`}
                style={{ transition: 'none' }}
                />
              ) : (
                <ChevronRight className={`w-4 h-4 ${
                  isActiveParent 
                    ? 'text-primary' 
                    : 'text-material-grey-500 group-hover:text-primary'
                }`}
                style={{ transition: 'none' }}
                />
              )}
            </div>
          )}
        </button>

        {item.children && isExpanded && (
          <div className="ml-6 space-y-1">
            {item.children.map((child) => (
              <button
                key={child.id}
                onClick={() => handleChildClick(child)}
                className={`w-full flex items-center p-3 rounded-lg group relative ${
                  activeItem === child.id 
                    ? 'bg-white text-primary' 
                    : 'hover:bg-material-grey-50 text-material-grey-600 hover:text-primary'
                }`}
                style={{
                  transition: 'none'
                }}
              >
                {activeItem === child.id && (
                  <div className="absolute left-0 top-1/2 transform -translate-y-1/2 w-1 h-6 bg-primary rounded-r-full"></div>
                )}
                
                <div className={`w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 ${
                  activeItem === child.id 
                    ? 'bg-primary/20 ml-3' 
                    : 'bg-material-grey-100 group-hover:bg-primary/10 ml-3'
                }`}
                style={{ transition: 'none' }}
                >
                  <child.icon className={`w-4 h-4 ${
                    activeItem === child.id 
                      ? 'text-primary' 
                      : 'text-material-grey-500 group-hover:text-primary'
                  }`}
                  style={{ transition: 'none' }}
                  />
                </div>
                <span className={`text-sm font-medium ml-3 ${
                  activeItem === child.id 
                    ? 'text-primary' 
                    : 'text-material-grey-600 group-hover:text-primary'
                }`}
                style={{ transition: 'none' }}
                >
                  {child.title}
                </span>
              </button>
            ))}
          </div>
        )}
      </div>
    );
  }, [expandedItems, activeItem, activeParentItem, toggleExpanded, handleChildClick]);

  return (
    <>
      {isOpen && (
        <div 
          className="fixed inset-0 bg-black/50 z-40 lg:hidden"
          onClick={handleClose}
        />
      )}

      <div className={`
        fixed top-0 left-0 h-screen bg-white z-50 transition-transform duration-300 ease-in-out
        ${isOpen ? 'translate-x-0' : '-translate-x-full'}
        lg:relative lg:translate-x-0
        w-72 border-r border-material-grey-200 flex flex-col
      `}>
        <div className="flex items-center justify-between p-6 border-b border-material-grey-200 bg-white flex-shrink-0">
          <div className="flex items-center space-x-4">
            <div className="w-10 h-10 bg-gradient-to-br from-primary to-primary-600 rounded-xl flex items-center justify-center">
              <CloudIcon className="w-6 h-6 text-white" />
            </div>
            <div>
              <h2 className="text-xl font-bold text-material-grey-900">
                筋斗云
              </h2>
              <p className="text-material-grey-600 text-sm">
                智能私有云盘系统
              </p>
            </div>
          </div>
          <Button
            onClick={handleClose}
            variant="ghost"
            size="icon"
            className="lg:hidden hover:bg-material-grey-100 text-material-grey-600"
          >
            <X className="w-5 h-5" />
          </Button>
        </div>

        <div className="flex-1 overflow-y-auto p-6 space-y-3">
          {isLoadingMenu ? (
            <div className="space-y-3">
              {[1, 2, 3, 4].map((i) => (
                <div key={i} className="p-4 rounded-xl bg-material-grey-100 animate-pulse">
                  <div className="flex items-center space-x-4">
                    <div className="w-10 h-10 bg-material-grey-200 rounded-xl"></div>
                    <div className="flex-1">
                      <div className="h-4 bg-material-grey-200 rounded mb-1"></div>
                      <div className="h-3 bg-material-grey-200 rounded w-2/3"></div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : menuItems.length > 0 ? (
            menuItems.map((item) => (
              <MenuItemComponent key={item.id} item={item} />
            ))
          ) : (
            <div className="text-center py-8">
              <div className="w-16 h-16 bg-material-grey-200 rounded-full flex items-center justify-center mx-auto mb-4">
                <MenuSquare className="w-8 h-8 text-material-grey-500" />
              </div>
              <p className="text-material-grey-600 text-sm">暂无菜单数据</p>
            </div>
          )}
        </div>

        <div className="flex-shrink-0 p-6 border-t border-material-grey-200 bg-gradient-to-r from-material-grey-50 to-white">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <div className="bg-white rounded-xl p-4 border border-material-grey-200 hover:border-primary/30 cursor-pointer group transition-colors duration-200">
                <div className="flex items-center space-x-4">
                  <div className="w-12 h-12 bg-gradient-to-br from-primary to-primary-600 rounded-xl flex items-center justify-center">
                    {userInfo?.avatar ? (
                      <img 
                        src={userInfo.avatar} 
                        alt="头像" 
                        className="w-full h-full object-cover rounded-xl"
                      />
                    ) : (
                      <span className="text-lg font-bold text-white">
                        {userInfo?.nickName?.charAt(0) || userInfo?.realName?.charAt(0) || '用'}
                      </span>
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    {isLoadingUserInfo ? (
                      <div className="space-y-1">
                        <div className="h-4 bg-material-grey-200 rounded animate-pulse"></div>
                        <div className="h-3 bg-material-grey-200 rounded w-3/4 animate-pulse"></div>
                      </div>
                    ) : (
                      <>
                        <p className="text-sm font-semibold text-material-grey-800 truncate group-hover:text-primary transition-colors duration-200">
                          {userInfo?.nickName || userInfo?.realName || '用户'}
                        </p>
                        <div className="space-y-1">
                          {userInfo?.currentRoleName && (
                            <span className="text-xs text-material-grey-600 block">
                              {userInfo.currentRoleName}
                            </span>
                          )}
                        </div>
                      </>
                    )}
                  </div>
                  <div className="opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                    <ChevronDown className="w-4 h-4 text-material-grey-400" />
                  </div>
                </div>
              </div>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-56">
              <DropdownMenuItem onClick={handleProfileClick}>
                <User className="w-4 h-4 mr-2" />
                个人资料
              </DropdownMenuItem>
              <DropdownMenuItem onClick={handleSwitchRole}>
                <RefreshCw className="w-4 h-4 mr-2" />
                切换角色
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem 
                onClick={handleLogout}
                className="text-red-600 focus:text-red-600"
              >
                <LogOut className="w-4 h-4 mr-2" />
                注销登录
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      <RoleSwitchDialog
        open={showRoleSwitchDialog}
        onOpenChange={handleRoleSwitchDialogChange}
        onRoleSwitch={handleRoleSwitch}
      />
    </>
  );
};

export default Sidebar;
